<template>
  <div class="home-container">
    <!-- 头部 -->
    <header class="header">
      <div class="logo-container">
        <div class="title">萌宠情报局</div>
      </div>
      <div class="search-box">
        <input type="text" v-model="searchKeyword" placeholder="搜索宠物或周边商品..." @keyup.enter="searchProducts" />
        <button class="search-btn" @click="searchProducts">
          <el-icon class="search-icon"><Search /></el-icon>
          <span>搜索</span>
        </button>
      </div>
      <div class="user-actions-container">
        <el-button
          v-if="isAdmin"
          type="danger"
          size="small"
          class="admin-entry-btn"
          @click="goToAdmin"
        >
          进入管理页面
        </el-button>
        <div class="user-actions">
          <router-link to="/ai-assistant" class="action-icon ai-icon">
            <el-icon><ChatDotRound /></el-icon>
          </router-link>
          <div class="user-menu" v-if="isLoggedIn">
            <el-dropdown>
              <span class="action-icon user-icon">
                <el-icon><User /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToProfile">个人中心</el-dropdown-item>
                  <el-dropdown-item @click="logout" divided>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <router-link v-else to="/login" class="action-icon user-icon">
            <el-icon><User /></el-icon>
          </router-link>
          <router-link to="/cart" class="action-icon cart-icon">
            <el-icon><ShoppingCart /></el-icon>
          </router-link>
          <router-link to="/orders" class="action-icon order-icon">
            <el-icon><Tickets /></el-icon>
          </router-link>
          <router-link to="/wallet" class="action-icon wallet-icon">
            <el-icon><Wallet /></el-icon>
          </router-link>
        </div>
      </div>
    </header>

    <!-- 宠物分类 -->
    <div class="pet-categories">
      <div class="category-item" v-for="(category, index) in petCategories" :key="category.id" @click="filterByCategory(category.id)">
        <div class="category-icon">
          <el-icon v-if="index === 0"><Star /></el-icon>
          <el-icon v-else-if="index === 1"><Food /></el-icon>
          <el-icon v-else-if="index === 2"><Goods /></el-icon>
          <el-icon v-else-if="index === 3"><House /></el-icon>
          <el-icon v-else-if="index === 4"><Brush /></el-icon>
          <el-icon v-else-if="index === 5"><Bowl /></el-icon>
          <el-icon v-else-if="index === 6"><Chicken /></el-icon>
          <el-icon v-else-if="index === 7"><Mug /></el-icon>
          <el-icon v-else><Dessert /></el-icon>
        </div>
        <div class="category-name">{{ category.name }}</div>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 热门宠物推荐 -->
      <div class="content-section">
        <div class="section-title">热门宠物推荐</div>
        <div class="hot-pets">
          <div class="pet-card" v-for="pet in hotPets" :key="pet.id" @click="viewProductDetail(pet.id)">
            <div class="pet-image">
              <img :src="pet.imageUrl" :alt="pet.name">
            </div>
            <div class="pet-info">
              <div class="pet-name">{{ pet.name }}</div>
              <div class="pet-desc">{{ pet.description }}</div>
              <div class="pet-price">¥{{ pet.price }}</div>
              <button class="detail-btn" @click.stop="viewProductDetail(pet.id)">查看详情</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 限时促销 -->
      <div class="content-section" v-if="promotions.length > 0">
        <div class="section-title">限时促销</div>
        <div class="promotions">
          <div class="promotion-card" v-for="promotion in promotions" :key="promotion.id" @click="viewProductDetail(promotion.id)">
            <div class="promotion-image">
              <img :src="promotion.imageUrl" :alt="promotion.name">
              <div class="discount-badge" v-if="promotion.discount">
                {{ Math.round((1 - promotion.discount) * 100) }}% OFF
              </div>
            </div>
            <div class="promotion-info">
              <div class="promotion-name">{{ promotion.name }}</div>
              <div class="promotion-desc">{{ promotion.description }}</div>
              <div class="promotion-price">
                <span class="current-price">¥{{ typeof promotion.currentPrice === 'number' ? promotion.currentPrice.toFixed(2) : promotion.currentPrice }}</span>
                <span class="original-price">¥{{ typeof promotion.originalPrice === 'number' ? promotion.originalPrice.toFixed(2) : promotion.originalPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 附近店铺 -->
      <div class="content-section">
        <div class="section-title">
          <div class="title-content">
            <span>附近店铺</span>
            <div class="location-info">
              <el-icon class="location-icon"><LocationFilled /></el-icon>
              <span class="location-text">{{ locationMethod }}</span>
              <el-button
                type="primary"
                size="small"
                @click="showLocationSelector"
                class="location-selector-btn"
              >
                <el-icon><Pointer /></el-icon>
                选择位置
              </el-button>
            </div>
          </div>
        </div>
        <div class="nearby-stores">
          <div v-if="nearbyStores.length === 0" class="empty-state">
            <div class="empty-icon">🏪</div>
            <div class="empty-title">暂无附近店铺</div>
            <div class="empty-description">
              没有找到您附近的宠物店铺，您可以：
            </div>
            <div class="empty-actions">
              <el-button type="primary" @click="showLocationSelector" round>
                <el-icon><Pointer /></el-icon>
                选择其他位置
              </el-button>
              <el-button @click="fetchNearbyStores" round>
                <el-icon><Refresh /></el-icon>
                重新定位
              </el-button>
            </div>
          </div>
          <div class="store-card" v-for="store in nearbyStores" :key="store.id">
            <div class="store-image">
              <img :src="store.imageUrl || '@/assets/homelogo.png'" :alt="store.name">
            </div>
            <div class="store-info">
              <div class="store-name">{{ store.name }}</div>
              <div class="store-address">{{ store.address }}</div>
              <div class="store-distance">{{ store.distance }}km</div>
              <div class="store-hours">营业时间: {{ store.businessHours }}</div>
              <div class="store-actions">
                <button class="map-btn" @click="showStoreLocation(store)">查看地图</button>
                <button class="detail-btn" @click="viewStoreDetail(store.id)">查看详情</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <div class="bottom-nav">
      <div class="nav-item active">
        <i class="nav-icon">
          <el-icon><HomeFilled /></el-icon>
        </i>
        <span>首页</span>
      </div>
      <div class="nav-item">
        <router-link to="/cart">
          <i class="nav-icon">
            <el-icon><ShoppingCart /></el-icon>
          </i>
          <span>购物车</span>
        </router-link>
      </div>
      <div class="nav-item">
        <router-link to="/user">
          <i class="nav-icon">
            <el-icon><User /></el-icon>
          </i>
          <span>个人中心</span>
        </router-link>
      </div>
    </div>

    <!-- 地图弹窗 -->
    <el-dialog v-model="mapDialogVisible" title="店铺位置" width="80%">
      <div class="map-container" ref="mapContainer" style="height: 400px;"></div>
    </el-dialog>

    <!-- 位置选择器弹窗 -->
    <el-dialog v-model="locationSelectorVisible" title="选择您的位置" width="500px">
      <div style="margin-bottom: 20px;">
        <p style="color: #666; font-size: 14px;">
          如果自动定位不准确，请手动选择您所在的城市：
        </p>
      </div>

          <div class="location-grid">
        <div
          v-for="location in presetLocations"
          :key="location.name"
          class="location-item"
          @click="selectPresetLocation(location)"
        >
          <div class="location-name">{{ location.name }}</div>
          <div class="location-coords">{{ location.lng }}, {{ location.lat }}</div>
        </div>
      </div>

      <div style="margin-top: 20px; text-align: center;">
        <el-button @click="locationSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="forceGetUserLocation">强制重新定位</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import { 
  User, 
  ShoppingCart, 
  HomeFilled, 
  ChatDotRound, 
  LocationFilled, 
  Pointer, 
  Refresh, 
  Tickets, 
  Wallet,
  Search, // 添加搜索图标
  // 添加分类图标
  Goods,
  Food,
  Star,
  Brush,
  Chicken,
  Dessert,
  Bowl,
  House,
  Mug
} from '@element-plus/icons-vue'
import { TOKEN_KEY } from '../config'
import {  ElButton, ElIcon } from 'element-plus'; // 引入ElButton

// 扩展Window接口以包含AMap
declare global {
  interface Window {
    AMap: any;
    createAiChat: (options: { appId: string; iconPosition: string }) => void;
  }
}

interface StoreData {
  id: number;
  name: string;
  address: string;
  distance: number;
  businessHours: string;
  imageUrl: string;
  longitude: number;
  latitude: number;
}

interface CategoryData {
  id: number;
  name: string;
  iconUrl: string;
  sortOrder?: number;
}

const router = useRouter()
const searchKeyword = ref('')
const mapDialogVisible = ref(false)
const mapContainer = ref(null)
const selectedStore = ref<StoreData | null>(null)
const userLocation = ref({ lng: 116.404, lat: 39.915 }) // 默认位置（北京）
const locationSelectorVisible = ref(false)
const locationAccuracy = ref<number>(0) // 定位精度
const locationMethod = ref<string>('默认') // 定位方法

// 计算是否在厦门地区
const isInXiamen = computed(() => {
  return userLocation.value.lng > 118 && userLocation.value.lng < 124 &&
         userLocation.value.lat > 24 && userLocation.value.lat < 26
})

// [ADDED] 新增计算属性，用于判断当前用户是否为管理员
const isAdmin = computed(() => {
  return localStorage.getItem('userRole') === '1';
});

// [ADDED] 新增跳转到后台管理页面的方法
const goToAdmin = () => {
  router.push('/admin');
};

// 检查登录状态
const isLoggedIn = computed(() => {
  return !!localStorage.getItem(TOKEN_KEY)
})

// 退出登录
const logout = () => {
  // 清除所有本地存储的用户信息
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem('userId')
  localStorage.removeItem('username')

  // 清除axios默认请求头
  delete axios.defaults.headers.common['Authorization']

  ElMessage.success('已退出登录')

  // 跳转到登录页
  router.push('/login')
}

// 跳转到个人中心
const goToProfile = () => {
  router.push('/user')
}

// 宠物分类
const petCategories = ref<CategoryData[]>([])

// 获取商品分类
const fetchCategories = async () => {
  try {
    const response = await axios.get('/api/user/categories')

    if (response.data && Array.isArray(response.data)) {
      // 转换响应数据格式，只获取一级分类（parentId为null或0的分类）
      petCategories.value = response.data
        .filter((category: any) => !category.parentId || category.parentId === 0)
        .map((category: any) => ({
          id: category.id,
          name: category.name,
          iconUrl: category.iconUrl || '@/assets/homelogo.png',
          sortOrder: category.sortOrder
        }))
        .sort((a: CategoryData, b: CategoryData) => (a.sortOrder || 0) - (b.sortOrder || 0)) // 按排序字段排序
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
    // 错误时设置为空数组，不使用默认数据
    petCategories.value = []
  }
}

// 热门宠物
const hotPets = ref<any[]>([])

// 促销商品
const promotions = ref<any[]>([])

// 附近店铺
const nearbyStores = ref<StoreData[]>([])

// 搜索商品
const searchProducts = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  // 调用搜索API
  router.push({
    path: '/search',
    query: { keyword: searchKeyword.value }
  })
}

// 按分类过滤
const filterByCategory = (categoryId: number) => {
  router.push(`/category/${categoryId}`)
}

// 查看商品详情
const viewProductDetail = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 查看店铺详情
const viewStoreDetail = (storeId: number) => {
  router.push(`/store/${storeId}`)
}

// 显示店铺位置地图
const showStoreLocation = (store: any) => {
  selectedStore.value = store
  mapDialogVisible.value = true

  // 在对话框显示后渲染地图
  setTimeout(() => {
    if (window.AMap && mapContainer.value) {
      renderMap()
    } else {
      ElMessage.warning('地图服务暂不可用')
    }
  }, 300)
}

// 渲染地图
const renderMap = () => {
  if (!window.AMap || !mapContainer.value || !selectedStore.value) {
    console.error('地图渲染条件不满足:', {
      hasAMap: !!window.AMap,
      hasContainer: !!mapContainer.value,
      hasStore: !!selectedStore.value
    })
    return
  }

  try {
    const store = selectedStore.value!  // 已经在上面检查过了，不会为null
    
    const map = new window.AMap.Map(mapContainer.value, {
      zoom: 15,
      center: [store.longitude, store.latitude]
    })

    // 添加店铺标记
    new window.AMap.Marker({
      position: [store.longitude, store.latitude],
      title: store.name,
      map: map
    })

    // 添加用户位置标记
    new window.AMap.Marker({
      position: [userLocation.value.lng, userLocation.value.lat],
      title: '我的位置',
      icon: '//webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      map: map
    })

    // 检查是否有Driving插件，如果没有则动态加载
    if (window.AMap.Driving) {
      // 添加两点间的路线
      const driving = new window.AMap.Driving({
        map: map,
        panel: false
      })

               driving.search(
           [userLocation.value.lng, userLocation.value.lat],
           [store.longitude, store.latitude]
         )
    } else {
      // 动态加载Driving插件
      window.AMap.plugin('AMap.Driving', () => {
        const driving = new window.AMap.Driving({
          map: map,
          panel: false
        })

        driving.search(
          [userLocation.value.lng, userLocation.value.lat],
          [store.longitude, store.latitude]
        )
      })
    }
  } catch (error) {
    console.error('地图渲染失败:', error)
    ElMessage.warning('地图加载失败，请稍后重试')
  }
}

// 获取用户位置
const getUserLocation = () => {
  console.log('开始获取用户位置...')

  // 首先尝试从localStorage获取缓存的位置
  const cachedLocation = localStorage.getItem('userLocation')
  const cachedMethod = localStorage.getItem('locationMethod')
  
  if (cachedLocation) {
    try {
      const location = JSON.parse(cachedLocation)
      userLocation.value = location
      locationMethod.value = cachedMethod || '缓存位置'
      console.log('使用缓存位置:', location)
      fetchNearbyStores()
      return
    } catch (e) {
      console.warn('缓存位置数据无效，重新获取')
    }
  }

  if (navigator.geolocation) {
    // 显示获取位置的提示
    ElMessage.info('正在获取您的位置信息...')
    
    navigator.geolocation.getCurrentPosition(
      (position) => {
        console.log('获取位置成功:', position.coords)
        console.log('用户真实坐标 - 经度:', position.coords.longitude, '纬度:', position.coords.latitude)

        userLocation.value = {
          lng: position.coords.longitude,
          lat: position.coords.latitude
        }
        locationAccuracy.value = position.coords.accuracy || 0
        locationMethod.value = 'GPS定位'

        // 保存用户位置到localStorage，供其他页面使用
        localStorage.setItem('userLocation', JSON.stringify(userLocation.value))
        localStorage.setItem('locationMethod', locationMethod.value)
        localStorage.setItem('locationTimestamp', Date.now().toString())

        console.log('更新用户位置为:', userLocation.value)
        console.log('用户位置详细信息 - 经度:', userLocation.value.lng, '纬度:', userLocation.value.lat)
        
        ElMessage.success('位置获取成功')
        fetchNearbyStores()
      },
      (error) => {
        console.error('获取位置失败:', error)
        
        let errorMessage = ''
        switch(error.code) {
          case 1: // PERMISSION_DENIED
            errorMessage = '位置访问被拒绝，请在浏览器设置中允许位置访问'
            break
          case 2: // POSITION_UNAVAILABLE
            errorMessage = '无法获取位置信息，请检查GPS或网络连接'
            break
          case 3: // TIMEOUT
            errorMessage = '位置获取超时，将使用默认位置'
            break
          default:
            errorMessage = '位置获取失败，将使用默认位置'
        }
        
        ElMessage.warning(errorMessage)
        console.log('使用默认位置（北京天安门）:', userLocation.value)
        locationMethod.value = '默认位置'
        fetchNearbyStores() // 使用默认位置获取店铺
      },
      {
        timeout: 15000, // 增加到15秒超时
        enableHighAccuracy: false, // 改为false，优先速度而非精度
        maximumAge: 600000 // 增加到10分钟内的位置缓存有效
      }
    )
  } else {
    console.error('浏览器不支持地理位置服务')
    ElMessage.warning('您的浏览器不支持地理位置服务，将使用默认位置')
    console.log('使用默认位置（北京天安门）:', userLocation.value)
    locationMethod.value = '浏览器不支持'
    fetchNearbyStores() // 使用默认位置获取店铺
  }
}

// 显示位置选择器
const showLocationSelector = () => {
  locationSelectorVisible.value = true
}

// 选择预设位置
const selectPresetLocation = (location: { lng: number, lat: number, name: string }) => {
  console.log('用户手动选择位置:', location.name, location)
  userLocation.value = { lng: location.lng, lat: location.lat }
  locationAccuracy.value = 0
  locationMethod.value = `手动选择(${location.name})`
  
  // 保存用户位置到localStorage，供其他页面使用
  localStorage.setItem('userLocation', JSON.stringify(userLocation.value))
  localStorage.setItem('locationMethod', locationMethod.value)
  
  locationSelectorVisible.value = false
  fetchNearbyStores()
}

// 强制重新获取位置（清除缓存）
const forceGetUserLocation = () => {
  // 清除位置缓存
  localStorage.removeItem('userLocation')
  localStorage.removeItem('locationMethod')
  localStorage.removeItem('locationTimestamp')
  
  locationSelectorVisible.value = false
  getUserLocation()
}

// 预设城市位置
const presetLocations = [
  { lng: 118.094, lat: 24.479, name: '厦门市' },
  { lng: 121.473, lat: 31.231, name: '上海市' },
  { lng: 116.404, lat: 39.915, name: '北京市' },
  { lng: 113.264, lat: 23.129, name: '广州市' },
  { lng: 114.314, lat: 22.543, name: '深圳市' },
  { lng: 120.153, lat: 30.287, name: '杭州市' },
  { lng: 118.767, lat: 32.041, name: '南京市' },
  { lng: 104.066, lat: 30.572, name: '成都市' }
]

// 从API获取附近店铺
const fetchNearbyStores = async () => {
  try {
    console.log('正在获取附近店铺，用户位置:', userLocation.value)

    const response = await axios.get('/api/user/stores/nearby', {
      params: {
        lng: userLocation.value.lng,
        lat: userLocation.value.lat,
        distance: 50 // 搜索半径50公里
      }
    })

    console.log('附近店铺API响应status:', response.status)
    console.log('附近店铺API响应data:', response.data)
    console.log('响应数据类型:', typeof response.data)
    console.log('是否为数组:', Array.isArray(response.data))
    console.log('数组长度:', response.data ? response.data.length : '数据为空')

    if (response.data && Array.isArray(response.data)) {
      // 转换响应数据格式
      nearbyStores.value = response.data.map((store: any) => {
        console.log('处理店铺数据:', store)
        return {
          id: store.storeId, // 后端字段是storeId
          name: store.name,
          address: store.addressText, // 后端字段是addressText
          distance: parseFloat((store.distance || 0).toFixed(1)),
          businessHours: store.businessHours || '09:00-21:00',
          imageUrl: store.logoUrl || '@/assets/homelogo.png', // 后端字段是logoUrl
          longitude: store.longitude,
          latitude: store.latitude
        }
      })

      console.log('转换后的店铺数据:', nearbyStores.value)

      if (nearbyStores.value.length === 0) {
        console.log('API返回空数据，使用默认数据')
        useDefaultStores()
      }
    } else {
      console.log('API响应格式不正确，使用默认数据')
      useDefaultStores()
    }
  } catch (error) {
    console.error('获取附近店铺失败:', error)
    useDefaultStores()
  }
}

// 清理过期的位置缓存
const clearExpiredLocationCache = () => {
  const timestamp = localStorage.getItem('locationTimestamp')
  if (timestamp) {
    const cacheAge = Date.now() - parseInt(timestamp)
    const maxAge = 24 * 60 * 60 * 1000 // 24小时
    
    if (cacheAge > maxAge) {
      localStorage.removeItem('userLocation')
      localStorage.removeItem('locationMethod')
      localStorage.removeItem('locationTimestamp')
      console.log('清理过期的位置缓存')
    }
  }
}

// 使用默认店铺数据
const useDefaultStores = () => {
  // 不再使用硬编码的默认数据，只显示空状态
  console.log('没有找到附近店铺，显示空状态')
  nearbyStores.value = []
}

// 获取热门宠物和促销商品
const fetchFeaturedProducts = async () => {
  try {
    // 随机获取商品 - 不按类型筛选，直接获取随机商品
    const productsResponse = await axios.get('/api/user/products', {
      params: {
        current: 1,
        size: 12  // 增加获取数量，确保有足够的非折扣商品可用
      }
    })

    if (productsResponse.data && productsResponse.data.records) {
      const allProducts = productsResponse.data.records;

      // 先筛选出有折扣的商品（discount < 1.0）
      const discountedProducts = allProducts
        .filter((product: any) => product.discount && product.discount < 1.0)
        .map((promo: any) => ({
          id: promo.id,
          name: promo.name,
          description: promo.description || '限时优惠',
          currentPrice: Number((promo.price * promo.discount).toFixed(2)), // 计算折扣后价格
          originalPrice: promo.price,
          imageUrl: promo.mainImageUrl || '@/assets/homelogo.png',
          discount: promo.discount
        }));

      // 设置促销商品
      promotions.value = discountedProducts;

      // 筛选非折扣商品用于热门宠物展示
      // 创建折扣商品ID集合，用于快速查找
      const discountedIds = new Set(discountedProducts.map((item: any) => item.id));

      // 过滤掉已经在折扣区显示的商品
      const nonDiscountedProducts = allProducts
        .filter((product: any) => !discountedIds.has(product.id))
        .sort(() => Math.random() - 0.5)  // 随机排序
        .slice(0, 8)  // 改为获取8个商品
        .map((product: any) => ({
          id: product.id,
          name: product.name,
          description: product.description || '优质商品',
          price: product.price,
          imageUrl: product.mainImageUrl || '@/assets/homelogo.png'
        }));

      hotPets.value = nonDiscountedProducts;
    } else {
      // API调用失败时设置为空数组
      hotPets.value = [];
      promotions.value = [];
    }
  } catch (error) {
    console.error('获取商品数据失败:', error)
    // 错误时设置为空数组
    hotPets.value = [];
    promotions.value = [];
  }
}

onMounted(() => {
  // 清理过期缓存
  clearExpiredLocationCache()
  
  // 获取用户位置
  getUserLocation()

  // 获取商品数据
  fetchFeaturedProducts()

  // 获取分类数据
  fetchCategories()

  // 加载高德地图API
  if (!window.AMap) {
    const script = document.createElement('script')
    // 使用更通用的密钥或者移除密钥限制，同时加载驾车路线插件
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=66d6616317a208714cc4133d3d09cf57&plugin=AMap.Driving'
    script.async = true
    script.onload = () => {
      console.log('高德地图API加载成功')
    }
    script.onerror = () => {
      console.error('高德地图API加载失败')
    }
    document.head.appendChild(script)
  }


    })
</script>

<style scoped>

/* [ADDED] 为管理员入口按钮添加样式 */
.admin-entry-btn {
  margin-right: 15px; /* 与其他图标保持一些间距 */
  height: 32px;
  border-radius: 16px;
}

.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
}

/* 头部样式优化 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
  border-radius: 0 0 12px 12px;
}

.logo-container {
  display: flex;
  align-items: center;
  min-width: 150px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  background: linear-gradient(45deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.search-box {
  flex-grow: 1;
  display: flex;
  max-width: 500px;
  margin: 0 20px;
  position: relative;
}

.search-box input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 24px 0 0 24px;
  font-size: 15px;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  height: 46px;
}

.search-box input:focus {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
}

.search-btn {
  padding: 0 24px;
  background: linear-gradient(45deg, #409eff, #36d1dc);
  color: white;
  border: none;
  border-radius: 0 24px 24px 0;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
  height: 46px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 100px;
}

.search-btn:hover {
  background: linear-gradient(45deg, #66b1ff, #5cdbd3);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.search-icon {
  margin-right: 8px;
  font-size: 18px;
}

/* 用户操作区域样式优化 */
.user-actions-container {
  display: flex;
  align-items: center;
}

.user-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.action-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  color: #606266;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.action-icon:hover {
  color: #409eff;
  background-color: #ecf5ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.admin-entry-btn {
  margin-right: 15px;
  height: 36px;
  border-radius: 18px;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
  transition: all 0.3s ease;
}

.admin-entry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4);
}

/* 宠物分类样式优化 */
.pet-categories {
  display: flex;
  justify-content: space-around;
  padding: 25px 15px;
  background-color: white;
  margin: 20px 0;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10px 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 80px;
}

.category-item:hover {
  transform: translateY(-5px);
}

.category-icon {
  width: 64px;
  height: 64px;
  background: linear-gradient(145deg, #ffffff, #f0f0f0);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  font-size: 28px;
  color: #409eff;
}

.category-item:hover .category-icon {
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.2);
  background: linear-gradient(145deg, #f0f9ff, #e6f7ff);
  color: #1890ff;
  transform: scale(1.05);
}

.category-name {
  font-size: 14px;
  color: #606266;
  text-align: center;
  transition: all 0.3s ease;
}

.category-item:hover .category-name {
  color: #409eff;
  font-weight: 500;
}

/* 主要内容区 */
.main-content {
  flex: 1;
  padding: 0 15px;
}

.content-section {
  margin-bottom: 30px;
}

/* 章节标题 */
.section-title {
  padding: 15px 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  border-bottom: 2px solid #f0f0f0;
  margin-bottom: 20px;
}

.title-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.location-info {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f8f9fa;
  padding: 8px 15px;
  border-radius: 20px;
  border: 1px solid #e9ecef;
}

.location-icon {
  color: #409eff;
  font-size: 16px;
}

.location-text {
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.location-selector-btn {
  border-radius: 15px;
  padding: 8px 15px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.location-selector-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 热门宠物 */
.hot-pets {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 20px;
}

.pet-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
  background-color: white;
}

.pet-card:hover {
  transform: translateY(-5px);
}

.pet-image {
  height: 200px;
  overflow: hidden;
}

.pet-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pet-info {
  padding: 15px;
}

.pet-name {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 8px;
}

.pet-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.pet-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 15px;
}

.detail-btn {
  width: 100%;
  padding: 8px 0;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.detail-btn:hover {
  background-color: #66b1ff;
}

/* 促销区域 */
.promotions {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.promotion-card {
  display: flex;
  width: 100%;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s;
}

.promotion-card:hover {
  transform: translateY(-5px);
}

.promotion-image {
  width: 120px;
  height: 120px;
  min-width: 120px;
  overflow: hidden;
  position: relative;
}

.promotion-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.discount-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff4d4f;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.promotion-info {
  flex: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.promotion-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.promotion-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.promotion-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.current-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

/* 附近店铺 */
.nearby-stores {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 25px;
}

.store-card {
  display: flex;
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.store-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

.store-image {
  width: 140px;
  height: 140px;
  min-width: 140px;
  overflow: hidden;
  position: relative;
}

.store-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.store-card:hover .store-image img {
  transform: scale(1.1);
}

.store-info {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.store-name {
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 12px;
  color: #2c3e50;
  line-height: 1.3;
}

.store-address {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.store-address::before {
  content: "📍";
  font-size: 12px;
}

.store-distance {
  font-size: 13px;
  color: #27ae60;
  font-weight: 500;
  margin-bottom: 6px;
}

.store-hours {
  font-size: 13px;
  color: #95a5a6;
  margin-bottom: 15px;
}

.store-actions {
  display: flex;
  gap: 12px;
  margin-top: auto;
}

.map-btn, .detail-btn {
  flex: 1;
  padding: 10px 15px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.3s ease;
  text-align: center;
}

.map-btn {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  color: white;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.map-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
}

.detail-btn {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.detail-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: linear-gradient(145deg, #f8f9fa, #ffffff);
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.05);
  border: 2px dashed #e9ecef;
  margin: 20px 0;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.empty-description {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 30px;
  line-height: 1.5;
}

.empty-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 底部导航 - 只在移动端显示 */
.bottom-nav {
  display: none;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px 0;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.nav-item.active {
  color: #409eff;
}

.nav-icon {
  font-size: 24px;
  margin-bottom: 3px;
}

.nav-item a {
  text-decoration: none;
  color: inherit;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 响应式布局 */
/* 响应式设计优化 */
@media (max-width: 768px) {
  .home-container {
    padding-bottom: 60px;
  }

  .header {
    padding: 12px 15px;
    flex-wrap: wrap;
  }
  
  .logo-container {
    min-width: auto;
    margin-bottom: 10px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .search-box {
    order: 3;
    max-width: 100%;
    margin: 10px 0 0;
    width: 100%;
  }
  
  .user-actions-container {
    order: 2;
  }
  
  .user-actions {
    gap: 10px;
  }
  
  .action-icon {
    width: 36px;
    height: 36px;
  }
  
  .pet-categories {
    padding: 15px 10px;
  }
  
  .category-item {
    width: 70px;
    margin: 0 5px 10px;
  }
  
  .category-icon {
    width: 56px;
    height: 56px;
  }
  
  .category-icon img {
    width: 32px;
    height: 32px;
  }
  
  .category-name {
    font-size: 12px;
  }
  
  /* 位置信息响应式 */
  .title-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .location-info {
    width: 100%;
    justify-content: space-between;
  }

  /* 附近店铺响应式 */
  .nearby-stores {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .store-card {
    flex-direction: column;
  }

  .store-image {
    width: 100%;
    height: 200px;
    min-width: auto;
  }

  .store-info {
    padding: 15px;
  }

  .hot-pets {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(4, 1fr);
    gap: 15px;
  }
  
  .pet-card {
    min-width: auto;
  }

  .pet-image {
    height: 150px;
  }
}

@media (max-width: 480px) {
  .hot-pets {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(8, 1fr);
  }

  .promotion-card {
    flex-direction: column;
  }

  .promotion-image {
    width: 100%;
    height: 180px;
    min-width: auto;
  }

  .bottom-nav {
    display: flex;
    justify-content: space-around;
  }

  /* 空状态响应式 */
  .empty-state {
    padding: 40px 15px;
    margin: 15px 0;
  }

  .empty-actions {
    flex-direction: column;
    align-items: center;
  }

  .empty-actions .el-button {
    width: 200px;
  }
}

/* 地图容器样式 */
.map-container {
  width: 100%;
  height: 400px;
  border-radius: 4px;
}

/* 位置选择器样式 */
.location-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.location-item {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.location-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  transform: translateY(-2px);
}

.location-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.location-coords {
  font-size: 12px;
  color: #999;
}

@media (max-width: 768px) {
  .location-grid {
    grid-template-columns: 1fr;
  }
}
</style>
